Skip to content

Method: LruCache.CacheNode(URI, Class, Object)

1: /**
2: * Copyright (C) 2016 Czech Technical University in Prague
3: *
4: * This program is free software: you can redistribute it and/or modify it under
5: * the terms of the GNU General Public License as published by the Free Software
6: * Foundation, either version 3 of the License, or (at your option) any
7: * later version.
8: *
9: * This program is distributed in the hope that it will be useful, but WITHOUT
10: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11: * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12: * details. You should have received a copy of the GNU General Public License
13: * along with this program. If not, see <http://www.gnu.org/licenses/>.
14: */
15: package cz.cvut.kbss.jopa.sessions.cache;
16:
17: import java.net.URI;
18: import java.util.LinkedHashMap;
19: import java.util.Map;
20: import java.util.function.Consumer;
21:
22: /**
23: * @author ledvima1
24: */
25: class LruCache extends LinkedHashMap<LruCache.CacheNode, Object> {
26:
27: private final int capacity;
28: private final transient Consumer<CacheNode> removeCallback;
29:
30: public LruCache(int initialCapacity, Consumer<CacheNode> removeCallback) {
31: super(initialCapacity, 1.0f, true);
32: this.capacity = initialCapacity;
33: this.removeCallback = removeCallback;
34: }
35:
36: @Override
37: protected boolean removeEldestEntry(Map.Entry<CacheNode, Object> eldest) {
38: if (this.size() >= capacity) {
39: removeCallback.accept(eldest.getKey());
40: return true;
41: }
42: return false;
43: }
44:
45:
46: public static class CacheNode {
47: private final URI context;
48: private final Class<?> cls;
49: private final Object identifier;
50:
51: public CacheNode(URI context, Class<?> cls, Object identifier) {
52:• assert context != null;
53:• assert cls != null;
54:• assert identifier != null;
55:
56: this.context = context;
57: this.cls = cls;
58: this.identifier = identifier;
59: }
60:
61: public URI getContext() {
62: return context;
63: }
64:
65: public Class<?> getCls() {
66: return cls;
67: }
68:
69: public Object getIdentifier() {
70: return identifier;
71: }
72:
73: @Override
74: public boolean equals(Object o) {
75: if (this == o) return true;
76: if (o == null || getClass() != o.getClass()) return false;
77:
78: CacheNode cacheNode = (CacheNode) o;
79:
80: return context.equals(cacheNode.context) && cls.equals(cacheNode.cls) &&
81: identifier.equals(cacheNode.identifier);
82:
83: }
84:
85: @Override
86: public int hashCode() {
87: int result = context.hashCode();
88: result = 31 * result + cls.hashCode();
89: result = 31 * result + identifier.hashCode();
90: return result;
91: }
92: }
93: }